package _17_剑指Offer;

import _17_剑指Offer.datastrcute.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class _28_剑指Offer对称的二叉树 {

    // 迭代判断
    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;
        // 左右入队列，为空则判断终止条件
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root.left);
        queue.offer(root.right);
        while (!queue.isEmpty()) {
            // 弹出当前层的所有元素
            int size = queue.size();
            for (int i = size; i > 0; i-=2) {
                TreeNode first = queue.poll();
                TreeNode second = queue.poll();
                if (first == null && second == null) continue;
                // 不匹配条件
                if (first == null || second == null || first.val != second.val) return false;
                // 两值相同
                queue.offer(first.left);
                queue.offer(second.right);
                queue.offer(first.right);
                queue.offer(second.left);
            }
        }
        return true;
    }

    // 判断二叉树从根节点的左右子树是否相同 (递归)
    public boolean isSymmetric1(TreeNode root) {
        if (root == null) return true;
        return isMirrors(root.left, root.right);
    }

    public boolean isMirrors(TreeNode left, TreeNode right) {
        if (left == null && right == null) return true;

        // 其中一个为空，其中一个不为空，返回false
        if (left == null || right == null || left.val != right.val) return false;

        // 对称二叉树比较
        return isMirrors(left.left, right.right) && isMirrors(left.right, right.left);
    }

}
